package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecService {

    @Autowired
    private SpecGroupMapper groupMapper;

    @Autowired
    private SpecParamMapper paramMapper;

    public List<SpecGroupDTO> queryGroupOfCategory(Long id) {
        // 根据分类查询
        SpecGroup record = new SpecGroup();
        record.setCid(id);
        List<SpecGroup> list = groupMapper.select(record);
        // 健壮判断
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SpecGroupDTO.class);
    }

    public List<SpecParamDTO> queryParams(Long gid, Long cid, Boolean searching) {
        // 健壮判断
        if (gid == null && cid == null && searching == null) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        // 根据分组查询规格参数
        SpecParam record = new SpecParam();
        record.setGroupId(gid);
        record.setCid(cid);
        record.setSearching(searching);
        // 查询
        List<SpecParam> list = paramMapper.select(record);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SpecParamDTO.class);
    }

    public List<SpecGroupDTO> querySpecs(Long cid) {
        // 查询分类下的规格组
        List<SpecGroupDTO> groupList = queryGroupOfCategory(cid);

        // 查询分类下的所有规格
        List<SpecParamDTO> params = queryParams(null, cid, null);

        // 把params分组，分组的依据是groupId，id一致的作为一组。
        // 放到一个Map中，key是groupId,值是groupId一致的param的集合
        Map<Long, List<SpecParamDTO>> map = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        /*Map<Long, List<SpecParamDTO>> map = new HashMap<>();

        for (SpecParamDTO param : params) {
            Long groupId = param.getGroupId();
            // 判断，groupId是否已经存在
            if(!map.containsKey(groupId)){
                map.put(groupId, new ArrayList<>());
            }
            // 如果以及有list了，我取出list，把自己放进去
            map.get(groupId).add(param);
        }*/

        // 查询组内参数
        for (SpecGroupDTO group : groupList) {
            group.setParams(map.get(group.getId()));
        }
        return groupList;
    }
}
